<template>
  <div class="lbox">
    <img class="logo-img" src="@/assets/images/logo.png" alt="" />
    <div class="title">微澜AI智能交易平台</div>
    <van-tabs
      v-model:active="tabIndex"
      shrink
      title-inactive-color="#878B97"
      title-active-color="#000"
      color="#000"
      line-width="20px"
      background="#fff"
    >
      <van-tab title="邮箱登录">
        <div class="ibox">
          <div class="ili">
            <div class="ili-1">邮箱</div>
            <div class="ili-2">
              <van-field
                v-model="submitForm.email"
                placeholder="请输入邮箱"
                @blur="handleBlur"
                :border="false"
              />
              <div class="obox" v-show="isShow">
                <div
                  class="oli"
                  v-for="item in autoArr"
                  :key="item"
                  @click="chooseEmail(item)"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </div>
          <div class="ili">
            <div class="ili-1">验证码</div>
            <div class="ili-2">
              <van-field
                :border="false"
                v-model="submitForm.verificationCode"
                placeholder="请输入验证码"
              />
              <span class="fasong" @click="sendEmailCode">{{ emailText }}</span>
            </div>
          </div>
          <van-button class="btn" @click="handleLogin">登录</van-button>
          <!-- <div class="btn" @click="handleLogin">登录</div> -->
          <div class="tips">
            <!-- <span @click="toReg">去注册</span> -->
            <van-button type="primary" @click="toReg(2)" :loading="btnLoading2"
              >去注册</van-button
            >
            <van-button type="primary" @click="toHome">游客登录</van-button>
          </div>
        </div>
      </van-tab>
      <van-tab title="地址签名登录">
        <div class="ibox">
          <div class="ili">
            <div class="ili-1">当前地址</div>
            <div class="ili-2">
              <van-field v-model="currentAddress" readonly />
            </div>
          </div>
          <van-button class="btn" @click="toReg(1)" :loading="btnLoading1"
            >签名登录</van-button
          >
          <div class="tips">
            <van-button type="primary" @click="toReg(2)" :loading="btnLoading2"
              >去注册</van-button
            >
            <van-button type="primary" @click="toHome">游客登录</van-button>
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, computed, onMounted, watch } from "vue";
import { Toast } from "vant";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "@/store";
import { isEmail } from "@/utils/common";
import _ from "lodash";
const route = useRoute();
const router = useRouter();
const store = useStore();
const tabIndex = ref(0);
const btnLoading1 = ref(false);
const btnLoading2 = ref(false);
const invitationCode = route.query.invitationCode;
onMounted(() => {
  store.dispatch("users/getCurrentEthAddress");
  (window as any).ethereum.on("accountsChanged", function (accounts) {
    console.log(accounts[0]);
    store.commit("users/updateCurrentAddress", accounts[0]);
  });
  if (invitationCode) {
    toReg(2);
  }
});
const toHome = () => {
  router.push("/");
};
let emailText = ref<string | number>("发送");
const currentAddressAll = computed(() => store.state.users.currentAddress);
const currentAddress = computed(() => {
  const address = store.state.users.currentAddress;
  return (
    address.substring(0, 8) +
    "******" +
    address.substring(address.length - 8, address.length)
  );
});
const submitForm = reactive({
  email: "",
  verificationCode: "123456",
  address: currentAddress.value,
});
const emailArr = [
  "@qq.com",
  "@163.com",
  "@139.com",
  "@126.com",
  "@gmail.com",
  "@hotmail.com",
  "@yahoo.com",
  "@outlook.com",
];
const isShow = ref(false);
const autoArr = ref<any>([]);
watch(
  () => submitForm.email,
  (newVal) => {
    if (newVal) {
      if (newVal.includes("@")) {
        isShow.value = false;
      } else {
        autoArr.value = emailArr.map((v) => newVal + v);
        isShow.value = true;
      }
    } else {
      isShow.value = false;
    }
  }
);
const chooseEmail = (email: string) => {
  submitForm.email = email;
  isShow.value = false;
};
const handleBlur = () => {
  const timer = setTimeout(() => {
    isShow.value = false;
    clearTimeout(timer);
  }, 10);
};
// _.debounce(() => {
const toReg = (index: number) => {
  if (index === 2) {
    btnLoading2.value = true;
  }
  if (index === 1) {
    btnLoading1.value = true;
  }
  if (!currentAddressAll.value) {
    store.dispatch("users/getCurrentEthAddress");
    return;
  }
  store.dispatch("users/getSignMessage").then((res) => {
    btnLoading1.value = false;
    btnLoading2.value = false;
    if (res === true) {
      const email = store.state.users.infos.email;
      if (email) {
        Toast("当前地址已完成注册，前往首页");
        store.commit('users/updateIsEmailLogin',false)
        setTimeout(() => {
          router.push("/");
        }, 1000);
      } else {
        Toast("当前地址未注册");
        setTimeout(() => {
          router.push({
            path: "/register",
            query: {
              invitationCode,
            },
          });
        }, 1000);
      }
    } else {
      Toast("请先完成签名");
    }
  });
  const timer = setTimeout(() => {
    btnLoading1.value = false;
    btnLoading2.value = false;
    clearTimeout(timer);
  }, 2000);
};
// ,500);
const handleLogin = () => {
  // if(!currentAddressAll.value){
  //   store.dispatch('users/getCurrentEthAddress')
  //   return
  // }
  if (!isEmail(submitForm.email)) {
    Toast("请输入正确的邮箱");
    return;
  }
  if (!submitForm.verificationCode) {
    Toast("请输入验证码");
    return;
  }

  store
    .dispatch("users/emailLogin", {
      email: submitForm.email,
      verificationCode: submitForm.verificationCode,
    })
    .then((res) => {
      if (res) {
       store.commit('users/updateIsEmailLogin',true)
        Toast("登录成功");
        router.push("/");
      }
    });
};
const sendEmailCode = () => {
  if (!isEmail(submitForm.email)) {
    Toast("请输入正确的邮箱");
    return;
  }
  if (emailText.value === "发送") {
    emailText.value = 60;
    const timer = setInterval(() => {
      if (emailText.value <= 0) {
        emailText.value = "发送";
        clearInterval(timer);
        return;
      }
      (emailText.value as number) -= 1;
    }, 1000);
    store
      .dispatch("users/sendEmailCodeL", {
        email: submitForm.email,
        type: 3,
      })
      .then((res) => {
        Toast(res.msg || res.data);
      });
  }
};
</script>

<style lang="scss" scoped>
.lbox {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.logo-img {
  position: absolute;
  top: 40px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
}
.title {
  position: absolute;
  top: 140px;
  left: 0;
  width: 100%;
  font-size: 18px;
  color: #000;
  text-align: center;
}
.ibox {
  margin: 20px 20px 0;
  .ili {
    display: flex;
    flex-direction: column;
    margin-bottom: 14px;
    .ili-1 {
      font-size: 13px;
      color: #000;
      margin-bottom: 10px;
    }
    .ili-2 {
      background-color: #f1f1f1;
      border-radius: 4px;
      height: 38px;
      position: relative;
      .obox {
        min-width: 150px;
        max-height: 160px;
        overflow-y: scroll;
        padding: 0 10px;
        background: #fff;
        color: #000;
        border-radius: 4px;
        position: absolute;
        top: calc(100% + 5px);
        left: 0;
        z-index: 9999;
        .oli {
          font-size: 14px;
          display: flex;
          align-items: center;
          height: 32px;
        }
      }
      .fasong {
        font-size: 13px;
        color: #36b4ea;
        position: absolute;
        right: 16px;
        top: 50%;
        transform: translateY(-50%);
        z-index: 1001;
      }
    }
  }
}
.btn {
  width: 100% !important;
  height: 40px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  font-size: 14px !important;
  color: #fff !important;
  background: #36b4ea !important;
  border-radius: 3px !important;
  margin-top: 30px !important;
}
.tips {
  display: flex;
  justify-content: space-between;
  // border:1px solid red;
  margin-top: 24px;
  .van-button {
    background-color: #36b4ea !important;
    color: #fff !important;
    height: 34px;
  }
  // span {
  //   // color: #36b4ea;
  //   display: inline-block;
  //   padding:10px 15px;
  //   background-color: #2d2f3b;
  //   color:#f5f5f5;
  //   border-radius: 4px;

  // }
}
.van-tabs {
  margin-top: 180px;
  background: transparent;
}
</style>
